package com.lulin.mall.order.interceptor;

import com.lulin.common.constant.AuthConstant;
import com.lulin.common.vo.MemberVo;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 购物车拦截器
 *
 * @author lulin
 * @date 2022/12/21 16:13
 */
public class AuthInterceptor implements HandlerInterceptor {
    //本地线程对象
    public static ThreadLocal threadLocal = new ThreadLocal();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //放开支付宝的回调
        String requestURI = request.getRequestURI();
        boolean match = new AntPathMatcher().match("/orderPay/**", requestURI);
        if (match) {
            return true;
        }
        // 通过HttpSession获取当前登录的用户信息
        HttpSession session = request.getSession();
        Object attribute = session.getAttribute(AuthConstant.AUTH_SESSION_REDIS);
        if (attribute != null) {
            MemberVo memberVO = (MemberVo) attribute;
            threadLocal.set(memberVO);
            return true;
        }
        // 如果 attribute == null 说明没有登录，那么我们就需要重定向到登录页面
        session.setAttribute(AuthConstant.AUTH_SESSION_MSG, "请先登录");
        response.sendRedirect("http://auth.lulin.com/login.html");
        return false;
    }

}
